<?php

uses('sanitize');

class UsersController extends AppController {

	var $components = array('RequestHandler');
	var $name = 'Users';
	var $helpers = array('Html', 'Form', 'ajax' );
	//var $scaffold;

	/*function beforeFilter()
	{
		//$this->checkLayout();
		//$this->Security->requirePost('delete');
		$this->Security->requireAuth('knownusers', 'profile', 'delete');
		$this->Security->blackHoleCallback = 'invalid';
		
	}*/
	
/*	function invalid()
	{
		header ('HTTP/x 400 Bad Request');
		echo('<h1>Upward : erreur 400</h1>');
		echo('<p>Nous sommes désolé - Un problème est servenue, merci de renvoyer le formulaire une nouvelle fois.</p>');
		die;
	}*/

//action user	
/*	function index()
	{
		//unbind data not usefull
		$this->User->unbindModel(array('hasOne' => array('Customer'),
									'hasMany' => array('Post')
									));
	
		$username = $this->Session->read('user');
		if ($username)
		{
			$results = $this->User->findByUsername($username);
			$this->set('User', $results['User']);
			$this->set('last_login', $this->Session->read('last_login'));
		} else {
			$this->redirect('/users/login');
		}
	}
	


	function profile($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for User.');
			$this->redirect('/users/index');
		}
		//unbind data not usefull
		$this->User->unbindModel(array('hasMany' => array('Post')
									));
		$user = $this->User->read(null, $id);
	
		if($this->Acl->check($this->Session->read('user'), 'customer-'.$user['Customer']['id'], 'read')){
			$this->set('user', $user);
			
			if($this->Acl->check($this->Session->read('user'), 'customer-'.$id, 'update')){
				$this->set('showUpdate', TRUE);
			}else{
				$this->set('showUpdate', FALSE);
			}
			if($this->Acl->check($this->Session->read('user'), 'customer-'.$id, '*')){
				$this->set('showAdmin', TRUE);
			}else{
				$this->set('showAdmin', FALSE);
			}
		}else{
			$this->Session->setFlash('action impossible');
			$this->redirect('/users/index');
		}
	}

	function register() {
		//unbind data not usefull
		$this->User->unbindModel(array('hasMany' => array('Post')
									));
									
		$this->set('username_error', 'Le login doit être compris entre 5 et 40 charactères.');
		
		if(empty($this->data)) {
			$this->render();
		} else {
			$san = new Sanitize();
			$this->data['User']['username'] = $san->paranoid($this->data['User']['username']);
			$this->data['User']['email'] = $san->paranoid($this->data['User']['email'], array('@', '.', '-', '+'));
			$this->data['User']['first_name'] = $san->paranoid($this->data['User']['first_name'], array('-'));
			$this->data['User']['last_name'] = $san->paranoid($this->data['User']['last_name'], array(' ', '-'));
			
			if($this->User->validates($this->data))
			{
				if($this->User->findByUsername($this->data['User']['username']))
				{
					$this->User->invalidate('username');
					$this->set('username_error', 'Ce login est déjà utilisé.');
				}elseif($this->data['User']['password'] != $this->data['User']['password2']){
					$this->User->invalidate('password2');
				} else {
					$this->data['User']['password'] = md5($this->data['User']['password']);
				
					$this->cleanUpFields();
					if($this->User->save($this->data))
					{
						//add to customers
						$this->data['Customer']['user_id'] = $this->User->getLastInsertID();
						$this->data['Customer']['username'] = $this->data['User']['username'];
						$this->data['Customer']['email'] = $this->data['User']['email'];
						if(!empty($this->data['User']['first_name'])) $this->data['Customer']['first_name'] = $this->data['User']['first_name'];
						if(!empty($this->data['User']['last_name'])) $this->data['Customer']['last_name'] = $this->data['User']['last_name'];
						$this->User->Customer->save($this->data);
						
						//definition Acl
						$aro = new Aro();
						$aro->create($this->User->id, 'users', $this->data['User']['username']);
						$aco = new Aco();
						//$aco->create($this->User->id, null, $this->data['User']['username']);
						$aco->create($this->User->id, null, 'customer-'.$this->User->Customer->id);
						
						$this->Acl->allow($this->data['User']['username'], 'customer-'.$this->User->Customer->id);
						$this->Acl->deny($this->data['User']['username'], 'customer-'.$this->User->Customer->id, 'delete');
						$this->Acl->allow('dealers', 'customer-'.$this->User->Customer->id);
						$this->Acl->deny('dealers', 'customer-'.$this->User->Customer->id, 'delete');
						$this->Acl->allow('admins', 'customer-'.$this->User->Customer->id);
				
						$this->Session->setFlash('L\'enregistrement s\'est correctement déroulé.');
						$this->redirect('/users/index');
					} else {
						$this->flash('Un problème est survenu lors de l\'enregistrement des informations', '/users/register');
					}
				}
			} else {
				$this->validateErrors($this->User);
			}
		}
	}

	function ajaxlogin(){
		$this->render('ajaxlogin', 'ajax');
	}
	
	function login() {
		//unbind data not usefull
		$this->User->unbindModel(array('hasMany' => array('Post')
									));
		$this->set('error', false);
		if($this->data)
		{
			$san = new Sanitize();
			$cleaned_username = $san->paranoid($this->data['User']['username']);
			
			$results = $this->User->findByUsername($this->data['User']['username']);
			if($results && $results['User']['password'] == md5($this->data['User']['password']))
			{
				$this->Session->write('user', $this->data['User']['username']);
				$this->Session->write('last_login', $results['User']['last_login']);
				$this->Session->write('id', $results['User']['id']);
				$this->Session->write('customer_id', $results['Customer']['id']);
				
				if($this->Acl->check($this->data['User']['username'], '/bills', 'read')){
					$this->Session->write('level', 'dealers');
				}
				if($this->Acl->check($this->data['User']['username'], '/users/knownusers', '*')){
					$this->Session->write('level', 'admins');
				}	
				
				$results['User']['last_login'] = date("Y-m-d H:i:s");
				$this->User->save($results);
				$this->redirect('/users/index');
			} else {
				$this->Session->setFlash('Erreur de login ou de mot de passe');
				$this->data['User']['password'] = '';
			}
		}
	}
	
	function logout()
	{
		$this->Session->destroy();
		$this->redirect('/users/login');
	}

	function edit($id = null) {
		$success = false;
		$user = $this->User->read(null, $id);
		
		if(empty($this->data)) {
			if(!$id) {
				$this->Session->setFlash('Invalid id for User');
				$this->redirect('/users/index');
			}
			//
			if($this->Acl->check($this->Session->read('user'), 'customer-'.$user['Customer']['id'], 'update')){
				$this->data = $user;
			}else{
				$this->Session->setFlash('Action non autorisée');
				$this->redirect('/users/index');
			}
		} elseif($this->Acl->check($this->Session->read('user'), 'customer-'.$user['Customer']['id'], 'update')) {
			$this->User->cleanUpFields();		
			$san = new Sanitize();
			$this->data['User']['email'] = $san->paranoid($this->data['User']['email'], array('@', '.', '-', '+'));
			$this->data['User']['first_name'] = $san->paranoid($this->data['User']['first_name']);
			$this->data['User']['last_name'] = $san->paranoid($this->data['User']['last_name'], array(' '));
			$this->data['User']['website'] = $san->paranoid($this->data['User']['website'], array('/', '.', '-', '+'));
			$this->data['User']['about'] = $san->html($this->data['User']['about']);
			$this->data['Customer']['address'] = $san->html($this->data['Customer']['address']);
			
			$this->data['Customer']['user_id'] = $id;
			$this->data['Customer']['username'] = $this->data['User']['username'];
			$this->data['Customer']['first_name'] = $this->data['User']['first_name'];
			$this->data['Customer']['last_name'] = $this->data['User']['last_name'];
			$this->data['Customer']['email'] = $this->data['User']['email'];
			
			if($this->User->validates($this->data))
			{				
				
				if($customer = $this->User->Customer->findByUser_id($id, 'Customer.id')){
					$this->User->Customer->id = $customer['Customer']['id'];
				}

				if($this->User->Customer->editCustomer($this->data)){				
					if($this->User->save($this->data)) 
					{
						$this->Session->setFlash('The User has been saved');
						$this->redirect('/users/edit/'.$id);
					}
				}else{
					$this->Session->setFlash('Erreur customer');
					$this->redirect('/users/edit/'.$id);
				}
			} else {
				$this->validateErrors($this->User);
				$this->Session->setFlash('Corriger les erreurs suivantes.');
			}
		}else{
			$this->Session->setFlash('Action non autorisée');
			$this->redirect('/users/index');
		}
		
		if($this->Acl->check($this->Session->read('user'), $user['User']['username'], '*')){
			$this->set('showAdmin', TRUE);
		}else{
			$this->set('showAdmin', FALSE);
		}
	}
	
	function editpassword($id = null) {
		$user = $this->User->read(null, $id);
		if(empty($this->data)) {
			if(!$id) {
				$this->Session->setFlash('Invalid id for User');
				$this->redirect('/users/index');
			}
			//$this->data = $user;
		} elseif($this->Acl->check($this->Session->read('user'), 'customer-'.$user['Customer']['id'], 'update')) {
			if($this->User->validates($this->data))
			{
				if($this->data['User']['password'] != $this->data['User']['password2'])
				{
					$this->User->invalidate('password2');
					$this->Session->setFlash('Merci de corriger les erreurs suivantes.');
				}else{
					$this->data['User']['password'] = md5($this->data['User']['password']);
					if($this->User->save($this->data)) 
					{
						$this->Session->setFlash('The User has been saved');
						$this->redirect('/users/edit/'.$id);
					}
				}				
			} else {
				$this->Session->setFlash('Erreur, le mot de passe n\'à pas été sauvegardé.');
			}
			$this->redirect('/users/edit/'.$id);
		}else{
			$this->Session->setFlash('Action non autorisée');
			$this->redirect('/users/index');
		}
	}
	
//action dealer
/*
	function knownusers() {
		if($this->Acl->check($this->Session->read('user'), '/users/knownusers', 'read')){
			$this->User->recursive = 0;
			$this->set('knownusers',
				$this->User->findAll(null, array('id', 'username', 'first_name', 'last_name', 'website', 'last_login'), 'id DESC')
			);
		}else{
			$this->Session->setFlash('Action non autorisée');
			$this->redirect('/users/index');
		}
	}*/

//action admin

	function admin_index(){
		$this->pageTitle = 'Admin Users';
		$this->set('users', $this->User->findAll());
	}
	
	function admin_add(){
		$this->pageTitle = 'Add User';
		if($this->RequestHandler->isPost()){
			$this->cleanUpFields();
			if($this->User->save($this->data)){
				$this->Session->setFlash('User has been saved');
				$this->redirect('/admin/users');
			}else 
				$this->Session->setFlash('Please correct error below.');
		}
	}
	
	/*
	function delete($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for User');
			$this->redirect('/users/index');
		}
		$user = $this->User->read(null, $id);
		if($this->Acl->check($this->Session->read('user'), 'customer-'.$user['Customer']['id'], 'delete')){
			if($this->User->del($id)) {
				$aco = new Aco();
				$aco->delete($user['User']['username']);
				$this->Session->setFlash('The User deleted: id '.$id.'');
				$this->redirect('/users/index');
			}
		}else{
			$this->Session->setFlash('Action non autorisée');
			$this->redirect('/users/index');
		}
	}*/

}
?>
